package com.decent.component;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.decent.constant.Constant;
import com.decent.util.JwtUtils;
import com.decent.enums.MessageEnum;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author decent
 * @Create 2021/4/8 - 16:34
 * @Description
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            throw new JWTVerificationException(MessageEnum.VALID_ERROR.getMsg());
        }
        return Objects.nonNull(JwtUtils.verify(token, Constant.SECRET))  && !JwtUtils.timeout(token);

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
